import React, { Component, Fragment } from 'react'
import moment from 'moment'
import { connect } from 'react-redux'
import cs from 'classnames'
import qs from 'qs'

import {
  Spin,
  Button
} from 'antd'
import {
  Modal,
  Toast,
} from 'antd-mobile'
import Layout from 'component/layout'
import Alert from 'component/alert'
import Empty from 'component/empty'
import SuccessModal from 'component/successModal'
import PullToRefresh from 'component/pullToRefresh'
import HeaderLayout from 'layout/header'

import { formatMoney } from 'config/money'
import { formatTitle } from 'config/title'

import { getPreselect, removePreSelect, lockHouse } from 'model/user'

import { loading, fail, success, hideToast } from 'utils/toast'

import style from './index.less'

const {
  Content
} = Layout

const { alert } = Modal

@connect(state => ({
  user: state.user,
  building: state.building
}), {
  getPreselect,
  lockHouse,
  removePreSelect
})
export default class App extends Component {
  constructor (props) {
    super(props)

    this.state = {
      visibleDetail: false,
      visibleSuccess: false,

      houseDetailData: {}
    }
  }

  componentDidMount () {
    this.getPreselect()
  }

  getPreselect = (isRefresh) => {
    const {
      user: {
        phone
      },
      building: {
        propertyId,
        housePreiodId
      }
    } = this.props

    this.props.getPreselect({
      phone,
      propertyId,
      housePreiodId
    }, isRefresh)
  }

  handleDetail = (v, i, e) => {
    this.setState({
      houseDetailData: {
        ...v
      },
      visibleDetail: true
    })
  }

  handleLock = (v, i, e) => {
    // 是否选房结束
    const {
      building: {
        hobSpecificEndTime
      }
    } = this.props

    const now = moment()
    const mHobSpecificEndTime = moment(hobSpecificEndTime)

    if (mHobSpecificEndTime.isValid() && now.isAfter(mHobSpecificEndTime)) {
      alert('提示', '抱歉，选房已结束！', [
        { text: '知道了' },
      ])

      return
    }

    this.setState({
      houseDetailData: {
        ...v
      },
      // visibleSuccess: true
    }, async () => {
      // loading('锁房中')

      const [err, res] = await this.props.lockHouse({
        phone: this.props.user.phone,
        housePreiodId: this.props.building.housePreiodId,
        houseId: v.houseId,
      })

      // hideToast()
      this.setState({ visibleDetail: false })

      if (err) {
        alert('提示', err, [
          { text: '知道了' },
        ])

        return
      }

      // success('锁房成功')
      this.setState(prevState => ({
        houseDetailData: {
          ...prevState.houseDetailData,
          ...res[0]
        },

        visibleSuccess: true
      }))
    })
  }

  handleRemovePreSelect = (e) => {
    e.stopPropagation()

    alert('提示', <div>确认删除此备选吗?</div>, [
      { text: '取消' },
      { text: '确定', onPress: async () => {
        loading('删除备选中')

        const [err, res] = await this.props.removePreSelect({
          houseId: this.state.houseDetailData.houseId,
          phone: this.props.user.phone
        })

        hideToast()

        if (err) {
          fail(err)

          return
        }

        success('删除备选成功')

        this.setState({
          visibleDetail: false
        })
      } },
    ])
  }

  render () {
    const {
      visibleSuccess,
      houseDetailData,
      houseDetailData: {
        houseId,
        // 期数
        housePreiodName,
        // 栋数
        buildNumName,
        // 单元
        // 楼层
        floor,
        // 房号
        householdNo,

        hTotalPrice,
        hosUnitPrice,
        setInPrice,
        setInArea,
        hosUnitArea,

        stationaryMoney,
      }
    } = this.state

    const {
      user: {
        getPreSelectLoading,
        getPreSelectRefreshing,
        getPreSelectInit,
        getPreSelectMsg,

        lockHouse,
        lockHouseLimit,

        lockLoading,
        preSelectHouse
      },
      building: {
        manageEndDate,
        hobSpecificEndTime,
        propertyName,
        payWay
      }
    } = this.props

    let renderChildren = null

    const now = moment()
    const mHobSpecificEndTime = moment(hobSpecificEndTime)

    if (getPreSelectLoading && !getPreSelectInit) {
      renderChildren = <div className = 'loading-wrap'><Spin /></div>
    } else if (getPreSelectMsg) {
      renderChildren = (
        <PullToRefresh
          refreshing = { getPreSelectRefreshing }

          onRefresh = { () => this.getPreselect(true) }
        >
          <Empty type = 'network' text = { getPreSelectMsg } />
        </PullToRefresh>
      )
    } else if (!preSelectHouse.length) {
      renderChildren = (
        <PullToRefresh
          refreshing = { getPreSelectRefreshing }

          onRefresh = { () => this.getPreselect(true) }
        >
          <Empty text = '没有备选数据' />
        </PullToRefresh>
      )
    } else {
      renderChildren = (
        <PullToRefresh
          refreshing = { getPreSelectRefreshing }

          onRefresh = { () => this.getPreselect(true) }
        >
          <div className = { style['box-wrap'] }>
            {
              preSelectHouse.map((v, i) => (
                <Box
                  { ...v }

                  disabled = {
                    mHobSpecificEndTime.isValid() &&
                    now.isAfter(mHobSpecificEndTime) ||
                    lockHouse.length >= lockHouseLimit
                  }

                  key = { i }

                  onClick = { e => this.handleDetail(v, i, e) }
                  onLock = { e => this.handleLock(v, i, e) }
                />
              ))
            }
          </div>
        </PullToRefresh>
      )
    }

    return (
      <HeaderLayout
        title = '我的备选'
        flex
      >
        <Alert />
        <Content>
          { renderChildren }
        </Content>
        <Modal
          visible = { this.state.visibleDetail }
          onClose = { () => this.setState({ visibleDetail: false }) }
          animationType = 'slide-up'
          popup
        >
          <div className = { style['house'] }>
            <div className = { style['house-header'] }>
              <h1>{ propertyName }</h1>
              <a onClick = { this.handleRemovePreSelect } >
                删除
              </a>
            </div>
            <div className = { style['house-body'] }>
              <h2>
                {
                  formatTitle({
                    buildNumName,
                    floor,
                    householdNo,
                  })
                }
              </h2>
              <div className = { style['house-info'] }>
                <div className = { style['house-info-title'] }>房屋总价</div>
                <div className = { style['house-info-value'] }>
                  {
                    hTotalPrice
                  }
                </div>
              </div>
              {
                stationaryMoney ?
                  <div className = { style['house-info'] }>
                    <div className = { style['house-info-title'] }>定金金额</div>
                    <div className = { style['house-info-value'] }>{ stationaryMoney }</div>
                  </div> :
                  null
              }
              <div className = { style['house-info'] }>
                <div className = { style['house-info-title'] }>套内单价</div>
                <div className = { style['house-info-value'] }>{ setInPrice }</div>
              </div>
              <div className = { style['house-info'] }>
                <div className = { style['house-info-title'] }>套内面积</div>
                <div className = { style['house-info-value'] }>{ setInArea }</div>
              </div>
              <div className = { style['house-info'] }>
                <div className = { style['house-info-title'] }>建面单价</div>
                <div className = { style['house-info-value'] }>{ hosUnitPrice }</div>
              </div>
              <div className = { style['house-info'] }>
                <div className = { style['house-info-title'] }>建筑面积</div>
                <div className = { style['house-info-value'] }>{ hosUnitArea }</div>
              </div>
            </div>
            <div className = { style['house-footer'] }>
              <Button className = { style['house-footer-action'] } type = 'primary' onClick = { () => this.setState({ visibleDetail: false }) }>关闭</Button>
            </div>
          </div>
        </Modal>
        <SuccessModal
          propertyName = { propertyName }
          housePreiodName = { housePreiodName }
          buildNumName = { buildNumName }
          floor = { floor }
          householdNo = { householdNo }
          stationaryMoney = { stationaryMoney }
          payWay = { payWay }

          manageEndDate = { manageEndDate }

          visible = { visibleSuccess }
          onCancel = { () => this.setState({ visibleSuccess: false }) }
          onOk = { () => {
            if  (payWay === '3') {
              this.props.history.push(`/pay?${ qs.stringify(houseDetailData) }`)
            } else {
              this.setState({ visibleSuccess: false })
            }
          } }
        />
      </HeaderLayout>
    )
  }
}

const Box = props => {
  const {
    onLock = f => f,
    onClick = f => f,
    sold,
    disabled,

    // 期数
    housePreiodName,
    // 栋数
    buildNumName,
    // 单元
    // 楼层
    floor,
    // 房号
    householdNo,

    // 备选人数
    preSelectNum,

    // 总价
    hTotalPrice,
    hosUnitPrice,
    hosUnitArea,
    setInPrice,
    setInArea,
  } = props

  const classString = cs(style['box'], {
    [style['box-sold']]: sold
  })

  function handleClick (e) {
    onClick(e)
  }

  function handleLock (e) {
    e.stopPropagation()

    onLock(e)
  }

  return (
    <div className = { classString } disabled = { disabled } onClick = { handleClick }>
      <div className = { style['box-content'] }>
        <h1>
          {
            formatTitle({
              housePreiodName,
              buildNumName,
              floor,
              householdNo,
            })
          }
        </h1>
        <div className = { style['box-info'] }>
          <div className = { style['box-info-title'] }>房屋总价</div>
          <div className = { style['box-info-value'] }>
            {
              hTotalPrice
            }
          </div>
        </div>
        <div className = { style['box-info'] }>
          <div className = { style['box-info-title'] }>备选人数</div>
          <div className = { style['box-info-value'] }>{ preSelectNum }</div>
        </div>
      </div>
      <div className = { style['box-status'] } onClick = { handleLock } />
    </div>
  )
}
